package com.lihaozhe.handler;

import com.lihaozhe.constant.CommonConstant;
import com.lihaozhe.util.response.ResponseResult;
import com.lihaozhe.util.servlet.BaseServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李昊哲
 * @version 1.0
 * 2021/11/28 15:50
 */
@Slf4j
@Component
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final CommonConstant commonConstant;

    public LoginAuthenticationSuccessHandler(CommonConstant commonConstant) {
        this.commonConstant = commonConstant;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取登陆人信息
        User user = (User) authentication.getPrincipal();
        log.info("LoginAuthenticationSuccessHandler获取account >>> {}",user.getUsername());
        // 处于安全原因 值为null
        log.info("LoginAuthenticationSuccessHandler获取authString >>> {}",user.getPassword());
        user.getAuthorities().forEach(authority -> log.info("LoginAuthenticationSuccessHandler获取权限 >>> {}",authority));
        ResponseResult result = ResponseResult.success();
        result.setLocation(request.getContextPath() + "/toSuccessPage");
        BaseServlet.printJsonObject(response,result);
    }
}